package cn.cdu.basics.security;

import cn.cdu.basics.security.jwt.JwtRoleFilter;
import cn.cdu.basics.utils.SecurityUtil;
import cn.cdu.basics.parameter.NoAuthenticationProperties;
import cn.cdu.basics.parameter.LoginProperties;
import cn.cdu.basics.security.jwt.AuthenticationFailHandler;
import cn.cdu.basics.security.jwt.AuthenticationSuccessHandler;
import cn.cdu.basics.security.jwt.AccessDeniedHandler;
import cn.cdu.basics.security.permission.MyFilterSecurityInterceptor;
import cn.cdu.basics.security.validate.ImageValidateFilter;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * SpringSecurity 配置
 */
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private LoginProperties loginProperties;

    @Autowired
    private NoAuthenticationProperties noAuthenticationProperties;

    @Autowired
    private UserDetailsServiceImpl userDetailsService;

    @Autowired
    private AuthenticationSuccessHandler authenticationSuccessHandler;

    @Autowired
    private AuthenticationFailHandler authenticationFailHandler;

    @Autowired
    private AccessDeniedHandler accessDeniedHandler;

    @Autowired
    private MyFilterSecurityInterceptor myFilterSecurityInterceptor;

    @Autowired
    private ImageValidateFilter imageValidateFilter;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private SecurityUtil securityUtil;

    @Override
    protected void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
        authenticationManagerBuilder.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
    }

    @Override
    @Operation(summary = "SpringSecurity配置")
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = httpSecurity.authorizeRequests();

        // 放行 Swagger 所需的路径
        registry.antMatchers(
                "/swagger-ui.html",
                "/swagger-ui/**",
                "/v3/api-docs",
                "/v3/api-docs/**",
                "/v2/api-docs",
                "/v2/api-docs/**",
                "/swagger-resources/**",
                "/webjars/**"
        ).permitAll();

        // 放行自定义白名单路径
        for (String url : noAuthenticationProperties.getAuthentication()) {
            registry.antMatchers(url).permitAll();
        }

        registry
                // 表单登录配置
                .and().formLogin()
                .loginPage("/zwz/common/needLogin")
                .loginProcessingUrl("/zwz/login")
                .permitAll()
                .successHandler(authenticationSuccessHandler)
                .failureHandler(authenticationFailHandler)
                // 允许 iframe
                .and().headers().frameOptions().disable()
                // 注销
                .and().logout().permitAll()
                // 所有请求必须认证
                .and().authorizeRequests().anyRequest().authenticated()
                // 允许跨域
                .and().cors()
                // 禁用 CSRF
                .and().csrf().disable()
                // JWT 采用无状态
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                // 权限不足处理
                .and().exceptionHandling().accessDeniedHandler(accessDeniedHandler)
                // 过滤器链
                .and()
                .addFilterBefore(imageValidateFilter, UsernamePasswordAuthenticationFilter.class)
                .addFilterBefore(myFilterSecurityInterceptor, FilterSecurityInterceptor.class)
                .addFilter(new JwtRoleFilter(authenticationManager(), loginProperties, stringRedisTemplate, securityUtil));
    }

}
